package com.yst.gateway.monitor.services.impl;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.yst.gateway.monitor.common.utils.JsonUtils;
import com.yst.gateway.monitor.common.utils.LoginUserCache;
import com.yst.gateway.monitor.common.utils.MessageUtils;
import com.yst.gateway.monitor.models.SysUsers;
import com.yst.gateway.monitor.services.SysUserInterfaceService;

@Service
@Scope("prototype")
public class SysUserInterfaceServiceImpl implements SysUserInterfaceService{

	private static final Logger logger = Logger.getLogger(SysUserInterfaceServiceImpl.class);
	
	/**
	 * 获取用户中心接口信息
	 * @param parmap
	 * @param Url
	 * @return
	 */
	public String getHttpConnection(Map<String, Object> parmap, String Url) {
		String result = "";
		try {
			URL url = new URL(Url);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");  
			conn.setInstanceFollowRedirects(true);          
			conn.setUseCaches(false);
			conn.setRequestProperty("User-Agent", "Fiddler");
			conn.setRequestProperty("Accept-Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", "application/json");
			conn.connect();
			DataOutputStream dataout = new DataOutputStream(conn.getOutputStream());
			String json = JsonUtils.format(parmap);
            logger.info("发送的参数：" + json.toString());
            dataout.writeBytes(json.toString());
            dataout.flush();
            dataout.close();
            System.out.println(conn.getResponseCode());
            BufferedReader buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String str= "";
			while((str = buffer.readLine()) != null) {
				result += str;
			}
            buffer.close();
            conn.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
		
	}
	
	/**
	 * 用户登陆
	 */
	@Override
	public SysUsers getByUser(String name, String password) {
		String userurl = MessageUtils.getMessage("loginUrl");
		SysUsers user = new SysUsers();
		try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("ACCode", "");
            map.put("Sign", "");
            map.put("AppCode", MessageUtils.getMessage("Appcode"));
            map.put("LoginName", name.trim());
            map.put("LoginPassword", password);
            map.put("PasswordStyle", 0);
            String result = getHttpConnection(map, userurl);
            Map<String, Object> usermap = new JsonUtils().parse(result, HashMap.class);
            Map<String, Object> userstr = (Map<String, Object>) usermap.get("UserLoginModel");
            if(userstr.get("UserUniqueCode") == null) {
            	user.setMessage(usermap.get("Message").toString());
            }else {
            	user.setSysUserId(userstr.get("UserUniqueCode").toString());
            	user.setSysUserName(userstr.get("LoginName").toString());
            	user.setSysUserPsw(userstr.get("LoginPassword").toString());
            	user.setMessage(usermap.get("Message").toString());
            	user.setSysUserDel(1);
            	user.setSysUserStatus(1);
            	user.setToken(userstr.get("UserToken").toString());
            }
            logger.info("字符串信息:" + result);
            logger.info("接口返回的结果信息：" + usermap.get("Message"));
            logger.info("接口返回的用户信息编号:" + userstr.get("UserUniqueCode"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	/**
	 * 登陆退出
	 */
	@Override
	public Map<String, Object> loginOut() {
		String loginout = MessageUtils.getMessage("loginOutUrl");
		Map<String, Object> resmap = new HashMap<String, Object>();
		try {
			logger.info("session中的信息:" + LoginUserCache.getUser());
			if(LoginUserCache.getUser() == null) {
				resmap.put("Message", "loginout");
			}else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("login_token", LoginUserCache.getUser().getToken());
				map.put("ACCode", "");
				map.put("AppCode", MessageUtils.getMessage("Appcode"));
				map.put("Sign", "");
				String result = getHttpConnection(map, loginout);
				resmap = new JsonUtils().parse(result.toString(), HashMap.class);
//				resmap = new MapUtils().format(result.toString());
				logger.info("接口返回的结果信息:" + resmap.get("Success") + "," + resmap.get("Message"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resmap;
	}

	/**
	 * 用户注册
	 */
	@Override
	public Map<String, Object> registerUser(SysUsers user) {
		String registerUrl = MessageUtils.getMessage("registerUrl");
		Map<String, Object> resmap = new HashMap<String, Object>();
		try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("ACCode", "");
            map.put("Sign", "");
            map.put("AppCode", MessageUtils.getMessage("Appcode"));
            map.put("LoginName", user.getSysUserName());
            map.put("LoginPassword", user.getSysUserPsw());
            map.put("PasswordStyle", 0);
            String result = getHttpConnection(map, registerUrl);
            logger.info("接口返回的字符串:" + result);
            Map<String, Object> usermap = new JsonUtils().parse(result, HashMap.class);
            logger.info("接口返回的结果信息:" + usermap.get("Success") + "," + usermap.get("Message") + "," + usermap.get("UserUniqueCode"));
            Map<String, Object> resultmap = (Map<String, Object>) usermap.get("UserLoginInfoModel");
            resmap.put("Success", usermap.get("UserUniqueCode")==null?usermap.get("Success").toString():resultmap.get("Success").toString());
            resmap.put("Message", usermap.get("UserUniqueCode")==null?usermap.get("Message").toString():resultmap.get("Message").toString());
            resmap.put("UserUniqueCode", usermap.get("UserUniqueCode")==null?resultmap.get("UserUniqueCode").toString():usermap.get("UserUniqueCode").toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resmap;
	}
	
	
}
